package com.enation.app.javashop.base.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebSocketService {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private MemberManager memberManager;

    //与某个客户端的连接对话,需要通过它给客户端发消息
    private static ConcurrentHashMap<String, Session> map =  new ConcurrentHashMap<>();


    public void webSocketPushMessage(String message) {
        logger.info("收到订单消息:" + message);
        groupSending(message);
    }

    /**
     * 建立连接
     */
    public boolean onOpen(Session session, String name) {
        if(StringUtil.isEmpty(name)){
            logger.info("连接对象为空");
            return false;
        }
        // 如果map中已经有了前端传来的 则把map中的已存在的 移除,并关闭连接
        if(map.containsKey(name)){
            // 移除
            onClose(name);
        }
        map.put(name,session);
        logger.info("[WebSocket] 连接成功，当前连接人数为："+map.size());
        return true;
    }

    /**
     * 关闭连接
     * 关闭连接 移除连接人
     */
    public void onClose(String name) {
        if(StringUtil.isEmpty(name)){
            logger.info("关闭连接对象不存在" + name);
            return;
        }
        Session session = map.remove(name);
        try {
            if(session != null){
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("[WebSocket]退出成功，当前连接人数为：" + map.size());
    }

    /**
     * 指定发送
     */
    private void appointSending(String name, String message) {
        if(StringUtil.isEmpty(name) || StringUtil.isEmpty(message) ){
            logger.info("指定发送对象不存在" + name);
            return;
        }
        map.get(name).getAsyncRemote().sendText(message);
    }

    // 群发
    public void groupSending(String message) {
        logger.info("推送下单消息:" + message);
        for (String name : map.keySet()) {
            try {
                appointSending(name,message);
            }catch (Exception e){
                // 推送失败 删除当前人
                onClose(name);
                logger.error("发送给指定"+ name + "报错, 错误信息" , e);
            }
        }
    }
}
